<?php defined('SYSPATH') or die('No direct script access.');

/*
*
*
*
*/

class Controller_Purchases_Select extends Controller_Admin
{

    /**
     *手动新建采购单
     *
     */
    public function before()
    {
        try {
            ACL::Required('purchase_order_select');
        } catch (HTTP_Exception_403 $e) {
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(true));
        }
        include_once(MODPATH.'/common/logs.php');
        include_once(MODPATH.'/commonapi/classes/purchaseApi.php');
        parent::before();
    }

    public function action_purchaseindex()
    {
        $this->title = __("VMI预约单查询");
        $purchase = Config::load('purchase_status');
        $show_flag = $own_pu_id = 0;
        $purchase_status = $purchase->purchaseorder;
        $user = User::active_user()->id;
        $msg = true;
        $enterprise_dominant = Kohana::$config->load('enterprise_dominant')->as_array();
        $stores = Kohana::$config->load('vmi_warehouse')->as_array();
        $select_condition['date_from'] = isset($_GET['date_from']) ? $_GET['date_from'] : '';
        $select_condition['date_to'] = isset($_GET['date_to']) ? $_GET['date_to'] : '';
        $select_condition['purchaseorder_id'] = isset($_GET['purchaseorder_id']) ? trim($_GET['purchaseorder_id']) : '';
        $select_condition['supplier_id'] = isset($_GET['supplier_id']) ? trim($_GET['supplier_id']) : '';
        $select_condition['supplier_name'] = isset($_GET['supplier_name']) ? trim($_GET['supplier_name']) : '';
        $select_condition['sku'] = isset($_GET['sku']) ? trim($_GET['sku']) : '';
        $select_condition['store'] = isset($_GET['store']) ? $_GET['store'] : '';
        $select_condition['status'] = isset($_GET['status']) ? $_GET['status'] : '';
        $select_condition['enterprise_dominant'] = isset($_GET['enterprise_dominant']) ? trim($_GET['enterprise_dominant']) : '';
        $select_condition['payway'] = isset($_GET['payway']) ? $_GET['payway'] :'';
        $select_condition['purchaseplaner'] = isset($_GET['purchaseplaner_id']) ? trim($_GET['purchaseplaner_id']) : '';
        $sql_info = "SELECT distinct po.* FROM purchaseorders po ";
        $sql_select = " WHERE 1 ";
        $condition = implode('::',$select_condition);
        if ($select_condition['date_from']) {
            $date_from = $select_condition['date_from'] . " 00:00:00";
            $sql_select .= " AND `purchaseorder_date`>= '" . $date_from . "' ";
        }
        if ($select_condition['date_to']) {
            $date_to = $select_condition['date_to'] . " 23:59:59";
            $sql_select .= " AND `purchaseorder_date`<= '" . $date_to . "' ";
        }
        if ($select_condition['purchaseorder_id']) {
            $sql_select .= " AND po.`id`= '" . $select_condition['purchaseorder_id'] . "' ";
        }
        if ($select_condition['supplier_name']) {
            $id = DB::select('supplier_id')->from('vmi_supplier_skus')->where('supplier_name','like','%'.$select_condition['supplier_name'].'%')->execute('newerp')->as_array('supplier_id');
            if($id){
                $sql_select .= " AND `supplier_id` in (" .implode(',',array_keys($id)) .")";
            }else{
                $msg = false;
            }

        }
        if ($select_condition['sku']) {
            $sql_info .= " ,purchaseorder_details pd ";
            $sql_select .= " AND `sku`= '" . $select_condition['sku'] . "' AND po.id = pd.purchaseorder_id ";
        }
        if ($select_condition['payway']) {
            $sql_select .= " AND `pay_way`= '" . $select_condition['payway'] . "' ";
        }
        if ($select_condition['store']) {
            $sql_select .= " AND po.`warehouseid`= '" . $select_condition['store'] . "' ";
        }
        if ($select_condition['status']){
            $sql_select .= " AND po.`status`= " . $select_condition['status'];
        }
        if ($select_condition['enterprise_dominant']) {
            $sql_select .= " AND `enterprise_dominant`= '" . $select_condition['enterprise_dominant'] . "' ";
        }
        if ($select_condition['purchaseplaner']) {
            $sql_select .= " AND `purchaseplaner`= '" . $select_condition['purchaseplaner'] . "' ";
        }
        $sql_info .= $sql_select;
        $sql_info .= " order by purchaseorder_date desc";
        $purchase_info = DB::query(Database::SELECT, $sql_info)->execute('newerp')->as_array();

        //计算总的查询记录
        $count = count($purchase_info);
        //分页
        $pagination = Pagination::factory(array(
            'items_per_page' => 10,
            'total_items' => $count,
            'uri' => $this->request->uri(),
        ));
        if(!isset($_GET['down'])||!$_GET['down']){
            $current_page = isset($_GET['page']) ? $_GET['page'] : 1;
            $sql_info .= "  LIMIT " . (($current_page - 1) * 10) . ",10";
        }
//            echo  DB::query(Database::SELECT, $sql_info)->compile('newerp');die;
        $result = DB::query(Database::SELECT, $sql_info)->execute('newerp')->as_array();
        $pay_ways = DB::select('id', 'paywayname')->from('payways')
            ->where('status', '!=', 1)
            ->execute('newerp')
            ->as_array('id', 'paywayname');

        foreach ($result as $key => &$value) {
            $supplier = supplierskus::getNameByIdForVmi($value['supplier_id']);
            $result[$key]['supplier_id'] = $supplier;
            $result[$key]['purchaseplaner'] = Erpuser::nick_by_id($value['purchaseplaner']);
//            $result[$key]['status'] = $purchase_status[$value['status']];
            $result[$key]['pay_way_name'] = isset($pay_ways[$value['pay_way']]) ? $pay_ways[$value['pay_way']] : '';
            $result[$key]['storeName'] = isset($stores[$value['warehouseid']]) ? $stores[$value['warehouseid']] : '未知仓库';
            $result[$key]['enterprise_dominant'] = isset($enterprise_dominant[$value['enterprise_dominant']]) ? $enterprise_dominant[$value['enterprise_dominant']] : '';
            $result[$key]['po_status'] = isset($statusArr[$value['pass']]) ? $statusArr[$value['pass']] : '未知状态';
        }
//        echo "<pre>";print_r($_GET);echo "</pre>";die;
        if (empty($result) || $msg ==false){
            Message::error('sorry，查询结果为空,请重新查询');
            $result = array();
        }
        if(isset($_GET['down'])&&$_GET['down']){
            $this->action_downCsv($result);die;
        }
        $user = User::active_user()->nick;
        $view = View::factory('select');
        $view->set('purchase_id', $user)
            ->set('payway', $pay_ways)
            ->set('user', $user)
            ->set("condition", $condition)
            ->set('stores', $stores)
            ->set('status', Kohana::$config->load('purchase_status')->get('purchaseorder'))
            ->set('warehouseid', Kohana::$config->load('vmi_warehouse')->as_array())
            ->set("result", $result)
            ->set('enterprise_dominant',$enterprise_dominant)
            ->set("pagination", $pagination);

        $this->response->body($view);
    }
    /**
     * 预约单下载
     */
    public function action_downCsv($data)
    {
        if(count($data)>0){
            set_time_limit(0);
            ini_set('memory_limit','2048M');

            $output = fopen('php://output', 'w') or die("can't open php://output");
            header("Content-Type: application/csv");
            header("Content-Disposition: attachment; filename=预约单导出.(" .date("Ymd").").csv");
            ob_end_clean();
            $firstLine = array(
                'id' =>'预约单号',
                'supplier_id' =>'供应商',
                'purchaseorder_date' =>'预约单时间',
                'purchaseplaner' =>'计划员',
                'money' =>'总金额',
                'pay_way_name' =>'付款方式',
                'status' =>'状态',
                'enterprise_dominant' =>'主体',
                'storeName' =>'仓库',
                'remark' =>'备注'
            );
            $status = Kohana::$config->load('purchase_status')->get('purchaseorder');
            fputcsv($output, array_values($firstLine));
            foreach ($data as &$_data) {
                if($_data['status']>=20 && $_data['status']<70 && $_data['is_pull']) {
                    $_data['status'] = $status[$_data['status']] . '(未推送)';
                } else {
                    $_data['status'] = $status[$_data['status']];
                }
                $_output = array();
                foreach ($firstLine as $key => $val) {
                    $_output[$key] = $_data[$key];
                }
                fputcsv($output, array_values($_output));
            }

            fclose($output) or die("can't close php://output");
            exit;
        }else{
            echo "<script>alert('数据为空');history.go(-1)</script>";die;
        }
    }
    /**
     * 采购单查询
     */
    public function action_searchpurchase()
    {
        $purchase = Config::load('purchase_status');
        $show_flag = $own_pu_id = 0;
        $purchase_status = $purchase->purchaseorder;
        $user = User::active_user()->id;
        $select_condition = array();
        $this->title = __("VMI预约单查询");
        $select_condition['date_from'] = isset($_GET['date_from']) ? $_GET['date_from'] : '';
        $select_condition['date_to'] = isset($_GET['date_to']) ? $_GET['date_to'] : '';
        $select_condition['purchaseplaner'] = isset($_GET['purchaseplaner']) ? trim($_GET['purchaseplaner']) : "";
        $select_condition['purchaseorder_id'] = isset($_GET['purchaseorder_id']) ? trim($_GET['purchaseorder_id']) : '';
        $select_condition['supplier_id'] = isset($_GET['supplier_id']) ? trim($_GET['supplier_id']) : '';
        $select_condition['sku'] = isset($_GET['sku']) ? trim($_GET['sku']) : '';
        $select_condition['enterprise_dominant'] = isset($_GET['enterprise_dominant']) ? trim($_GET['enterprise_dominant']) : '';
        $select_condition['status'] = isset($_GET['status']) ? $_GET['status'] : '';
        $select_condition['store'] = isset($_GET['store']) ? $_GET['store'] : -1;
        $select_condition['pass'] = isset($_GET['pass']) ? $_GET['pass'] : -1;
        if ($select_condition['purchaseorder_id']) {
            temporary::single_select($select_condition['purchaseorder_id']);
        }
        if (isset($select_condition['purchase_id']) && $select_condition['purchase_id'] != "") {

            $purchase_id = Erpuser::lookup_by_nick($select_condition['purchase_id']);
        }
        $condition = "";
        $condition .= $select_condition['date_from'] . "::" . $select_condition['date_to'] . "::" .
            $select_condition['purchase_id'] . "::" . $select_condition['purchaseorder_id'] . "::" .
            $select_condition['supplier_id'] . "::" . $select_condition['sku'] . "::" .
            $select_condition['status'] . "::" . $select_condition['store']."::".$select_condition['pass'];

        $sql_info = "SELECT distinct po.* FROM purchaseorders po ";
        $sql_select = " WHERE 1 ";

        if (isset($_GET['purchase_id']) && $_GET['purchase_id'] && !empty($purchase_id)) {
            $sql_select .= " AND `purchase_id` = " . $purchase_id;
        }

        if ($select_condition['date_from']) {
            $date_from = $select_condition['date_from'] . " 00:00:00";
            $sql_select .= " AND `purchaseorder_date`>= '" . $date_from . "' ";
        }
        if ($select_condition['date_to']) {
            $date_to = $select_condition['date_to'] . " 23:59:59";
            $sql_select .= " AND `purchaseorder_date`<= '" . $date_to . "' ";
        }

        if ($select_condition['store'] != -1) {
            $sql_select .= " AND `store`= '" . $select_condition['store'] . "' ";
        }

        if ($select_condition['pass'] != -1) {
            if($select_condition['pass'] == 1)
                $sql_select .= " AND `pass` = 1 ";
            else
                $sql_select .= " AND `pass` != 1 ";
        }


        if ($select_condition['purchaseorder_id'])
            $sql_select .= " AND po.`id`= '" . $select_condition['purchaseorder_id'] . "' ";
        if ($select_condition['supplier_id']) {

            $fields = array('id');
            $condition = "LIKE '%" . trim($select_condition['supplier_id']) . "%'";
            $condtions = array('name' => $condition);
            $suppliers = Newerpclientapi::getSuppliers($fields, $condtions);

            if (!empty($suppliers)) {
                $str = "(";
                $ids = "";
                foreach ($suppliers as $supplier) {
                    $ids .= $supplier['id'] . " ,";
                }
                $str .= substr($ids, 0, strlen($ids) - 1) . ")";
                $sql_select .= " AND `supplier_id` IN " . $str;
            }
        }
        if ($select_condition['status'] && $select_condition['status'] != 1)
            $sql_select .= " AND po.`status`= " . $select_condition['status'];
        if ($select_condition['sku']) {
            $sql_info .= " ,purchaseorder_details pd ";
            $sql_select .= " AND `sku`= '" . $select_condition['sku'] . "' AND po.id = pd.purchaseorder_id ";
        }
        $sql_info .= $sql_select;
        $sql_info .= " order by purchaseorder_date desc";

        if ((empty($purchase_id) && $select_condition['purchase_id']) ||
            (empty($suppliers) && $select_condition['supplier_id'])
        ) {
            $result = array();
            $pagination = "";

        } else {
            //            echo $sql_info;exit;
            $purchase_info = DB::query(Database::SELECT, $sql_info)->execute('newerp')->as_array();

            //计算总的查询记录
            $count = count($purchase_info);
            //分页
            $pagination = Pagination::factory(array(
                    'items_per_page' => 5,
                    'total_items' => $count,
                    'uri' => $this->request->uri(),
                ));
            $current_page = isset($_GET['page']) ? $_GET['page'] : 1;
            $sql_info .= "  LIMIT " . (($current_page - 1) * 5) . ",5";
            $result = DB::query(Database::SELECT, $sql_info)->execute('newerp')->as_array();

            $pay_ways = DB::select('id', 'paywayname')->from('payways')
                ->where('status', '!=', 1)
                ->execute('newerp')
                ->as_array('id', 'paywayname');
            $stores = array();
            $stores = Kohana::$config->load('vmi_warehouse')->as_array();
            //yuqing  获取状态

            $statusArr= array(0=>'符合',1=>'待审核',2=>'审核通过');

            //yuqing
            foreach ($result as $key => $value) {
                $sql = "SELECT `pay_date` FROM `purchaseorder_pays` WHERE `purchaseorder_id` =" . $value['id'] . " ORDER BY pay_date ";
                $result[$key]['pay_date'] = DB::query(Database::SELECT, $sql)->execute('newerp')->get('pay_date');
                //              ---------------------------------------kdw--------------------------------------
                //				$sql = "SELECT `vProviderName` FROM `erp_provider` WHERE `id` = ".$value['supplier_id'];
                //				$result[$key]['supplier_id'] = DB::query(Database::SELECT,$sql)->execute('readonlyerp')->get('vProviderName');

                $fields = array('name');
                $condtions = array('id' => '=' . $value['supplier_id']);
                $supplier = Newerpclientapi::getSuppliers($fields, $condtions);
                $result[$key]['supplier_id'] = $supplier[0]['name'];
                //				---------------------------------------kdw-end----------------------------------
                //$users= ORM::factory('user',$value['purchase_id']);
                $result[$key]['purchase_id'] = Erpuser::nick_by_id($value['purchase_id']);

                $result[$key]['status'] = $purchase_status[$value['status']];

                $result[$key]['pay_way_name'] = isset($pay_ways[$value['pay_way']]) ? $pay_ways[$value['pay_way']] : '';

                $result[$key]['createtype_string'] = (isset($value['createtype']) and $value['createtype'] == 2) ? "系统下单" : "人工下单";
                //判断当前用户是否为admin或者登录者，其它状态改为不可操作
                if ($value['purchase_id'] == $user || $user == 2) $show_flag = 1;

                //20150802添加过滤，如果是预付并且已经付款，不予以修改权限，添加下边一行代码
                if(!empty($result[$key]['pay_date']) && in_array($value['pay_way'], array(3, 4))) $show_flag = 0;
                if ($value['purchase_id'] == $user || $user == 2)$own_pu_id = 1;

                $result[$key]['show_flag'] = $show_flag;
                $result[$key]['own_pu_id'] = $own_pu_id;
                $result[$key]['storeName'] = isset($stores[$value['store']]) ? $stores[$value['store']] : '未知仓库';
                $result[$key]['po_status'] = isset($statusArr[$value['pass']]) ? $statusArr[$value['pass']] : '未知状态';
            }
        }

        if (empty($result)) Message::error('sorry，查询结果为空,请重新查询');
        $view = View::factory('select')
            ->set('user', $user)
            ->set("condition", $condition)
            ->set('sto', $_GET['store'])
            ->set('pass', $_GET['pass'])
            ->set('stores', purchase::getOutLandStock())
            ->set("result", $result)
            ->set("pagination", $pagination)
            ->set("date_from", $select_condition['date_from'])
            ->set("date_to", $select_condition['date_to'])
            ->set("sku", $select_condition['sku'])
            ->set("status", $select_condition['status'])
            ->set("purchase_id", $select_condition['purchase_id'])
            ->set("purchaseorder_id", $select_condition['purchaseorder_id'])
            ->set("supplier_id", $select_condition['supplier_id']);

        $this->response->body($view);
    }
    /**
     * 描述:删除
     * 作者:kelvin
     */
    public function action_delPurchaseOrder()
    {
        if($_GET['p_id']){
            $status = DB::select('status')->from('purchaseorders')->where('id','=',$_GET['p_id'])->execute('newerp')->current();
            if($status['status']!=10) {
                echo '状态不符合要求';
                die;
            }
            $result = DB::update('purchaseorders')->set(array('status'=>'100'))->where('id','=',$_GET['p_id'])->execute('newerp');
            if($result){
                logs::purchaseorder_log($_GET['p_id'], '取消成功');
                logs::write_log($_GET['p_id'],'purchaseorders/delete',1);
                echo '删除成功';die;
            }else{
                logs::write_log($_GET['p_id'],'purchaseorders/delete',0);
                echo '删除失败';die;
            }
        }else{
            echo '参数有误';die;
        }

    }
    /**
     *  重新推送预约单到分销直上
     *  作者:kelvin
     * */
    public function action_pull()
    {
        $api = PurchaseApi::purchasePull($_GET['id']);
        if($api['code']==200){
            $pull = "UPDATE `purchaseorders` SET `is_pull`= 1 WHERE `id`= " . (int)$_GET['id'] ;
            if(DB::query(Database::UPDATE, $pull)->execute('newerp')!=false){
                logs::write_log($_GET['id'],'purchaseorders/update',1,$pull);
                echo '推送成功';die;
            }else{
                logs::write_log($_GET['id'],'purchaseorders/update',1,$pull);
                echo '操作成功';die;
            }
        }else{
            $msg = '推送失败，可能的原因：<br>' . (isset($api['msg']) ? $api['msg'] : '接口响应失败');
            echo $msg;die;
        }
    }
}
